package com.heima.shopweb.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.shopweb.model.Cart;
import com.heima.shopweb.model.Item;
import com.heima.shopweb.service.CartService;
import com.heima.shopweb.service.GoodFeignService;
import com.heima.shopweb.service.OrderFeignService;
import com.zijie.core.util.JsonResult;
import com.zijie.goods.model.Goods;
import com.zijie.order.model.Order;
import com.zijie.order.model.OrderItem;
import com.zijie.order.model.search.OrderSearchBean;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("/shopping")
public class ShoppingOrderController {
    private GoodFeignService goodFeignService;
    private CartService cartService;
    private OrderFeignService orderFeignService;

    @Autowired
    public void setCartService(CartService cartService) {
        this.cartService = cartService;
    }
    @Autowired
    public void setGoodFeignService(GoodFeignService goodFeignService) {
        this.goodFeignService = goodFeignService;
    }

    @GetMapping("/orders/save")
    public String save(@RequestParam("memberId") Integer memberId,Model model,HttpSession session) {
        extracted(model, session);
        List<Cart> carts = (List<Cart>) model.getAttribute("carts");
        System.out.println(carts);
//        orderFeignService.saveOrderItem(carts);
        List<OrderItem> orderItems = new ArrayList<>();

        String string = UUID.randomUUID().toString();
        Order order = new Order();
        order.setOrderNo(string);
        order.setMemberId(memberId);
        order.setCreateTime(LocalDateTime.now());
        ResponseEntity<JsonResult<?>> save = orderFeignService.save(order);
        //订单项
        if (carts!=null && !carts.isEmpty()){
            for (Cart cart : carts) {
                OrderItem orderItem = new OrderItem();
                orderItem.setOrderId(string);
                orderItem.setGoodId(cart.getGoodId());
                orderItem.setCount(cart.getQty());
                orderItems.add(orderItem);
            }
        }
        ResponseEntity<JsonResult<?>> result = orderFeignService.saveOrderItem(orderItems);
        System.out.println("订单详情"+result);
//        System.out.println(save.getBody().getData());
        model.addAttribute("order", order);
        return "mall/pay-select";
    }
    
    @GetMapping("/payPage")
    public String payPage(@RequestParam("orderNo") String orderNumber,
                          @RequestParam("payType") Integer payType,
                          Model model,HttpSession session) {
        System.out.println("orderNumber = " + orderNumber);
        extracted(model, session);
        // 这里可以添加支付处理逻辑
        model.addAttribute("orderNo", orderNumber);
        model.addAttribute("payType", payType);
        // 添加订单对象到模型中
        Order order = new Order();
        order.setOrderNo(orderNumber);
        model.addAttribute("order", order);
        if (payType == 1){
            return "mall/alipay";
        }else  if (payType == 0){
            return "mall/wxpay";
        }
        return "mall/pay-select";
    }
    
    @GetMapping("/paySuccess")
    @ResponseBody
    public JsonResult<String> paySuccess(@RequestParam("payType") Integer payType,
                                         @RequestParam("orderNumber") String orderNumber) {
//        System.out.println(orderNumber);
        Order order=new Order();
        order.setOrderNo(orderNumber);
        order.setStatus("1");
        if (payType == 1){
            order.setPayType("支付宝");
        }else {
            order.setPayType("微信");
        }
        orderFeignService.update(order);
        // 模拟支付成功处理
        return new JsonResult<>("200", "支付成功", null);
    }
    
    private void extracted(Model model, HttpSession session) {
        Integer memberId = (Integer) session.getAttribute("memberId");
//        System.out.println("memberId = " + memberId);
        //查询当前用户的购物车数据
        List<Cart> carts = cartService.findByMemberId(memberId);
        model.addAttribute("carts", carts);
//        System.out.println("carts = " + carts);
        //根据购物车商品id查询商品
        List<Item> items = new ArrayList<>();
        BigDecimal total = new BigDecimal(0);
        for (Cart cart : carts) {
            Item item = new Item();
            item.setId(cart.getId());
            ResponseEntity<JsonResult<Goods>> byId = goodFeignService.findById(cart.getGoodId());
            JsonResult<Goods> jr = byId.getBody();
//            System.out.println("jr = " + jr);
            if (jr != null && jr.getCode().equals("200")) {
//                System.out.println("goods = " + jr.getData().getName());
                Goods goods = jr.getData();
                item.setNum(cart.getQty());
                item.setName(goods.getName());
                item.setPrice(goods.getPrice());
                item.setPic(goods.getPic());
                total = total.add(item.getPrice().multiply(new BigDecimal(item.getNum())));
                items.add(item);
            }
        }
        model.addAttribute("items", items);
        model.addAttribute("priceTotal", total);
    }

    @Autowired
    public void setOrderFeignService(OrderFeignService orderFeignService) {
        this.orderFeignService = orderFeignService;
    }
    @GetMapping("/orders")
    public String orderDetails(Model model, HttpSession session) {
        //1.查询当前用户的订单详情  这里的路径参数就是当前的订单，可以查看详情
//        System.out.println("orderNumber = " + orderNumber);
        Integer memberId = (Integer)session.getAttribute("memberId");
        OrderSearchBean osb = new OrderSearchBean();
        osb.setMemberId(memberId);
        ResponseEntity<JsonResult<List<Order>>> all = orderFeignService.findAll2(osb);
        if(all.getBody().getData()!=null){
            List<Map<String,Object>> orders = new ArrayList<>();
            List<Order> records = all.getBody().getData();
            for (Order record : records) {
                ResponseEntity<JsonResult<List<Map<String, Object>>>> byOrderId = orderFeignService.findByOrderId(record.getId());
                List<Map<String, Object>> orderItems = byOrderId.getBody().getData();
                Map<String, Object> order = Map.of("order", record, "orderItems", orderItems);
                orders.add(order);
            }
            model.addAttribute("orders",orders);
        }
        //2.调用feign（service包下OrderFeignService）去请求微服务去根据订单号寻找当前订单
        //3.设置对应属性，可以修改前端的html
        //4.返回给前端页面mall/order-detail
        return "mall/order-detail";
    }
    @PostMapping("/orders/update")
    @ResponseBody
    public JsonResult<?> update(@RequestBody Order order){
        ResponseEntity<JsonResult<?>> update = orderFeignService.update(order);
        boolean b = update.getBody().getData() != null;
        if( b){
            return JsonResult.success(order);
        }else{
            return (JsonResult.error("修改失败"));
        }

    }

}